package leetcode.每日一题;

import org.junit.Test;

/**
 * @author :songyaozhang
 * @date :Created 2021/8/10 9:44
 * @description :https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
 */
public class 寻找两个正序数组的中位数 {
    @Test
    public void test() {
        Solution solution = new Solution();
        System.out.println(solution.findMedianSortedArrays(new int[]{}, new int[]{3}));
    }

    class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            int len1 = nums1.length;
            int len2 = nums2.length;
            int len =  len1 + len2;
            if (len == 0) return 0;
            int middleIdx = len / 2;
            int prev = 0;
            int middle = 0;
            int i = 0;
            int j = 0;
            while (middleIdx-- >= 0) {
                prev = middle;
                if (i >= len1) {
                    middle = nums2[j++];
                } else if (j >= len2) {
                    middle = nums1[i++];
                } else
                    middle = nums1[i] < nums2[j] ? nums1[i++] : nums2[j++];
            }
            return len % 2 == 0 ? ((double) (prev + middle) / 2) : middle;
        }
    }
}
